package de.swta.freezay.admin.item;

import de.swta.freezay.components.ExtendedActionPanel;
import de.swta.freezay.components.TextInputPanel;
import de.swta.freezay.components.ActionPanel;
import de.swta.freezay.components.OptionContentPanel;
import de.swta.freezay.database.JPAController;
import de.swta.freezay.database.controller.exceptions.IllegalOrphanException;
import de.swta.freezay.database.controller.exceptions.NonexistentEntityException;
import de.swta.freezay.database.dbEntities.Item;
import de.swta.freezay.database.wicketAdapter.ItemDataProvider;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.NumberFormatter;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.validation.validator.RangeValidator;

/**
 *
 * @author JKorreck
 */
public class ItemView extends Panel {

    /** Formatter for Number inputs. */
    private static final NumberFormatter NUMBER_FORMATTER = 
                    new NumberFormatter(new DecimalFormat("####.##"));
    /** modal Window for editing an item. */
    private final ModalWindow modalWindow = new ModalWindow("modal");
    /** DataTable for items. */
    private DefaultDataTable itemTable;

    /**
     * Creates a new instance of ItemView.
     */
    public ItemView() {
        this("ItemView");
    }

    /**
     * Creates a new instance of ItemView.
     * @param id Id of the ItemView- Panel.
     */
    public ItemView(String id) {

        super(id);
        init();
    }

    /**
     * Initializes all components of the panel.
     */
    private void init() {


        /* Modal window. */
        add(modalWindow);

        /* Creating all columns for the data- View. */
        List<IColumn> columns = new ArrayList<IColumn>();

        columns.add(new AbstractColumn(new Model("Editieren")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem, String componentId, IModel model) {

                final Item i = (Item) model.getObject();

                /* Actionpanel for editing or removing an item in the dataView. */
                cellItem.add(new ExtendedActionPanel(componentId, new AjaxLink("select1") {

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        target.appendJavascript("Wicket.Window.unloadConfirmation = false;");
                        /* Selected item is edited. */
                        modalWindow.setContent(new ItemEditPanel(modalWindow.getContentId(),
                                                        i.getId(), true) {

                            @Override
                            public void confirmLinkClicked(AjaxRequestTarget target) {
                                /* Close the window after edit. */
                                modalWindow.close(target);
                                target.addComponent(ItemView.this.itemTable);
                            }
                        });

                        modalWindow.setTitle("Artikel editieren");
                        modalWindow.setInitialHeight(350);
                        modalWindow.setInitialWidth(400);
                        modalWindow.show(target);
                    }
                }, "Editieren", new AjaxLink("select2") {

                    @Override
                    public void onClick(AjaxRequestTarget target) {

                        if ((!i.isReserved()) && 
                                (!JPAController.ItemJpaController.isUsed(i.getId()))) {
                            /* An item can only be removed, when it is not used! */
                        target.appendJavascript("Wicket.Window.unloadConfirmation = false;");

                        modalWindow.setContent(new OptionContentPanel(modalWindow.getContentId()) {

                            public void onSelect(AjaxRequestTarget target, String selection) {

                                    try {
                                        /* Remove it from DB. */
                                        JPAController.ItemJpaController.destroy(i.getId());
                                    } catch (IllegalOrphanException ex) {
                                        Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                                    } catch (NonexistentEntityException ex) {
                                        Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    modalWindow.close(target);
                                    target.addComponent(ItemView.this.itemTable);
                            }

                            public void onCancel(AjaxRequestTarget target) {
                                modalWindow.close(target);
                            }

                        });
                        /* Confirm delete message. */
                        ((OptionContentPanel) modalWindow.get(
                                modalWindow.getContentId())).setMessageText(
                                "Wollen sie den Artikel '" + i.getName() + "' wirklich löschen?");

                        modalWindow.setTitle("Artikel löschen");

                        modalWindow.setInitialHeight(200);
                        modalWindow.setInitialWidth(300);
                        modalWindow.show(target);

                        } else {
                            /* Otherwise (when item is used) error message is shown. */
                            target.appendJavascript("alert('Löschen nicht möglich! " +
                                            " - Der Artikel wird bereits verwendet')");
                        }
                    }

                }, "Löschen"));
            }
        });

        columns.add(new PropertyColumn(new Model("Name"), "name", "name"));
        columns.add(new AbstractColumn(new Model("Beschreibung")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem, String componentId, IModel model) {

                Item i = (Item) model.getObject();
                cellItem.add(new MultiLineLabel(componentId, i.getDescription()));
            }
        });

        columns.add(new PropertyColumn(new Model("Kategorie"), "category.name", "category.name"));
        columns.add(new AbstractColumn(new Model("Menge")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem, String componentId, IModel model) {
                Item i = (Item) model.getObject();
                /* Amount is formatted. */
                try {
                    cellItem.add(new Label(componentId, ""
                            + NUMBER_FORMATTER.valueToString(i.getAmount())));
                } catch (ParseException ex) {
                    Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        columns.add(new PropertyColumn(new Model("Einheit"), "unit.name"));
        
        columns.add(new AbstractColumn(new Model("Anzahl\n (übrig)")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem, String componentId, IModel model) {
                final Item i = (Item) model.getObject();
                cellItem.add(new ActionPanel(componentId, "" 
                        + i.getCount() + " (" + i.getRemainingCount() + ")", new AjaxLink("select") {


                    @Override
                    public void onClick(AjaxRequestTarget target) {
//
                        /* Click on count button - a window is shown for chanign the item count. */
                        modalWindow.setContent(new TextInputPanel(modalWindow.getContentId(),
                                new RangeValidator(i.getMinimumCount(), 2000), i.getCount()) {

                            @Override
                            public void submitClicked(AjaxRequestTarget target, Object input) {

                                i.setCount((Integer) input);

                                try {
                                    /* Item is saved with new count. */
                                    JPAController.ItemJpaController.edit(i);
                                } catch (IllegalOrphanException ex) {
                                    Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                                } catch (NonexistentEntityException ex) {
                                    Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                                } catch (Exception ex) {
                                    Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                                }
                                modalWindow.close(target);
                                /* List is updated. */
                                target.addComponent(ItemView.this.itemTable);
                            }

                        });
                        modalWindow.setTitle("Anzahl editieren");
                        modalWindow.setInitialHeight(150);
                        modalWindow.setInitialWidth(200);
                        modalWindow.show(target);
                    }
                }));
            }
        });
        
        columns.add(new AbstractColumn(new Model("Preis")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem, String componentId, IModel model) {
                Item i = (Item) model.getObject();
                try {
                    cellItem.add(new Label(componentId, ""
                            + NUMBER_FORMATTER.valueToString(
                                    i.getPrice()) + " €"));

                } catch (ParseException ex) {
                    Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        columns.add(new AbstractColumn(new Model("+ / -")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem,
                                        String componentId, IModel model) {
                final Item i = (Item) model.getObject();

                cellItem.add(new InDecreasePanel(componentId) {
                    /* In/Decrease panel is added. */

                    @Override
                    public void onIncrease(AjaxRequestTarget target) {

                        final int oldCount = i.getCount();
                        i.increaseCount();
                        if (oldCount != i.getCount()) {
                            try {
                                /* Item with the inceased count is saved. */
                                JPAController.ItemJpaController.edit(i);
                            } catch (IllegalOrphanException ex) {
                                Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (NonexistentEntityException ex) {
                                Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (Exception ex) {
                                Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            target.addComponent(ItemView.this.itemTable);
                        }
                    }

                    @Override
                    public void onDecrease(AjaxRequestTarget target) {
                        final int oldCount = i.getCount();
                        /* Item with the inceased count is saved. */
                        i.decreaseCount();
                        if (oldCount != i.getCount()) {
                            try {
                                JPAController.ItemJpaController.edit(i);
                            } catch (IllegalOrphanException ex) {
                                Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (NonexistentEntityException ex) {
                                Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (Exception ex) {
                                Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            target.addComponent(ItemView.this.itemTable);
                        }
                    }
                });
            }
        });

        itemTable = new DefaultDataTable("table", columns, new ItemDataProvider(), 10);

        this.itemTable.setOutputMarkupId(true);
        /* table is added. */
        add(itemTable);

        /* link for adding an item */
        add(new AjaxLink("addItem") {

            @Override
            public void onClick(AjaxRequestTarget target) {

                modalWindow.setContent(new ItemEditPanel(modalWindow.getContentId(), -1, false) {

                    @Override
                    public void confirmLinkClicked(AjaxRequestTarget target) {
                        modalWindow.close(target);
                        target.addComponent(ItemView.this.itemTable);
                    }
                });
                modalWindow.setTitle("Artikel erstellen");
                modalWindow.setInitialHeight(350);
                modalWindow.setInitialWidth(400);
                modalWindow.show(target);
            }
        });
    }
}
